<template>
	<view class="orderDetails">
		<tui-navigation-bar :titleSize="18" :titleLineHeight="18" :titlefontWeight="800" :isOpacity="false"
			@init="initNavigation" title="订单管理" backgroundColor="#fff" color="#000">
			<view class="tui-header-icon" :style="{ marginTop: top + 'px' }">
				<tui-icon name="arrowleft" color="#333" @click="back"></tui-icon>
			</view>
		</tui-navigation-bar>
		<view class="orderDetails_content" :style="{ marginTop: marginTp + 'px' }">
			<!-- 倒计时 -->
			<view class="content_hader">
				<view class="hader_lt">
					<view class="lt_Title">
						<text class="invite" v-if="this.status*1===1">邀约中</text>
						<text class="invite" v-else-if="this.status*1===2">已确认</text>
						<text class="invite" v-else-if="this.status*1===3">待开始</text>
						<text class="invite" v-else-if="this.status*1===4">服务中</text>
						<text class="invite" v-else-if="this.status*1===5">待评价</text>
						<text class="invite" v-else-if="this.status*1===6">已完成</text>
						<text class="invite" v-else-if="this.status*1===7">已关闭</text>
						<text class="invite" v-else-if="this.status*1===8">拒绝</text>
					</view>
					<view class="lt_time" v-if="this.status*1===4"><text>还剩{{countdown}}结束</text></view>
				</view>
				<image class="hader_rt" v-if="this.status*1===1" src="/static/user/my/yaoyuezhong@2x.png"></image>
				<image class="hader_rt" v-else-if="this.status*1===2" src="/static/user/my/yiqueren@2x.png"></image>
				<image class="hader_rt" v-else-if="this.status*1===3" src="/static/user/my/icon_fuwuzhong@2x.png">
				</image>
				<image class="hader_rt" v-else-if="this.status*1===4" src="/static/user/my/daipingjia@2x.png"></image>
				<image class="hader_rt" v-else src="/static/user/my/yiwancheng@2x.png"></image>
			</view>
			<!-- 信息 -->
			<view class="content_info">
				<view class="info_item">
					<view class="item_left">
						<text>商家名称</text>
					</view>
					<view class="item_right">
						<text>{{inviteMerchant.merchantName}}</text>
					</view>
				</view>
				<view class="info_item" style="padding-top: 30rpx;">
					<view class="item_left">
						<text>球房位置</text>
					</view>
					<view class="item_right">
						<text>{{inviteMerchant.address}}</text>
					</view>
				</view>
				<view class="info_item" style="padding-top: 30rpx;">
					<view class="item_left">
						<text>球房电话</text>
					</view>
					<view class="item_right">
						<text>{{inviteMerchant.phoneNumber}}</text>
					</view>
				</view>
			</view>
			<!-- 教练 -->
			<view class="content_tutor">
				<view class="content">
					<view class="content_lt">
						<image class="image"
							:src="ossUrl + (orderDetails.assistant&&orderDetails.assistant.masterImg) || ''"></image>
					</view>
					<view class="content_rt">
						<view class="tp">
							<view class="tp_lt">
								<text>{{orderDetails.assistant&&orderDetails.assistant.assistantName}}</text>
								<image style="width: 36rpx;height: 36rpx;padding-left: 20rpx;padding-top: 6rpx;"
									src="/static/user/icon_chu.png"></image>
							</view>
							<text class="tp_rt">￥{{orderDetails.ordersVo&&orderDetails.ordersVo.orderAmount}}</text>
						</view>
						<view class="ct">
							<text class="ct_lt">{{orderDetails.assistant&&orderDetails.assistant.categoryName}}</text>
							<text class="ct_rt">距离:{{orderDetails.ordersVo&&orderDetails.ordersVo.distance || 0}}km</text>
						</view>
						<view class="bt">
							<text>￥{{orderDetails.assistant&&orderDetails.assistant.rates}}/小时</text>
						</view>
					</view>
				</view>
				<view class="flex align-center justify-between mx-2 fs-24 ft777777 mb-1">
					<text>车程计价{{orderDetails.ordersVo&&orderDetails.ordersVo.transportFeeUnitPrice||0}}元/km</text>
					<view class="ft333333 flex align-center">车费：<text
							class="ft63d6d3 font-weight-bold fs-28">￥{{orderDetails.ordersVo&&orderDetails.ordersVo.transportFee || 0}}</text>
					</view>
				</view>
				<view class="bottom">
					<view class="total"><text>合计:</text><text
							class="totalPrice">￥{{orderDetails.ordersVo&&orderDetails.ordersVo.actualAmount}}</text>
					</view>
				</view>
			</view>
			<!-- 下单时间 -->
			<view class="order_numTime">
				<view class="info_item">
					<view class="item_left">
						<text>订单号</text>
					</view>
					<view class="item_right">
						<text>{{orderDetails.ordersVo&&orderDetails.ordersVo.id}}</text>
						<tui-icon margin="4rpx" size="20" name="order"></tui-icon>
					</view>
				</view>
				<view class="info_item" style="padding-top: 30rpx;">
					<view class="item_left">
						<text>下单时间</text>
					</view>
					<view class="item_right">
						<text>{{orderDetails.ordersVo&&orderDetails.ordersVo.orderTime}}</text>
					</view>
				</view>
				<view class="info_item" style="padding-top: 30rpx;">
					<view class="item_left">
						<text>拒绝原因</text>
					</view>
					<view class="item_right">
						<text>{{orderDetails.invite&&orderDetails.invite.refuseReason}}</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部操作栏 -->
		<view class="orderDetails_footer">
			<tui-form-button @click="orderClick(orderDetails,'支付')" margin="0 0 0 20rpx" v-if="this.status*1===2"
				width="160rpx" size="28" height="60rpx" background="#63d6d3" radius="100rpx">立即支付</tui-form-button>
			<tui-form-button @click="orderClick(orderDetails,'取消订单')" margin="0 0 0 20rpx"
				v-if="this.status*1===1||this.status*1===2||this.status*1===3" width="160rpx" size="28" height="60rpx"
				plain background="#63d6d3" color="#63d6d3" radius="100rpx">取消订单</tui-form-button>
			<tui-form-button @click="orderClick(orderDetails,'一件续费')" margin="0 0 0 20rpx" v-if="this.status*1===4"
				width="160rpx" size="28" height="60rpx" plain background="#63d6d3" color="#63d6d3"
				radius="100rpx">一件续费</tui-form-button>
			<tui-form-button @click="orderClick(orderDetails,'联系教练')" margin="0 0 0 20rpx"
				v-if="this.status*1===3 || this.status*1===4  || this.status*1===5  || this.status*1===6" width="160rpx"
				size="28" height="60rpx" background="#63d6d3" radius="100rpx">联系教练</tui-form-button>
			<tui-form-button @click="orderClick(orderDetails,'删除订单')" margin="0 0 0 20rpx"
				v-if="this.status*1===5||this.status*1===6" width="160rpx" size="28" height="60rpx" plain
				background="#63d6d3" color="#63d6d3" radius="100rpx">删除订单</tui-form-button>
			<tui-form-button @click="orderClick(orderDetails,'立即评价')" margin="0 0 0 20rpx" v-if="this.status*1===5"
				width="160rpx" size="28" height="60rpx" background="#63d6d3" radius="100rpx">立即评价</tui-form-button>
		</view>
		<tutor-renew-popup :place="place" @clickRenew="clickRenew" :visible="isVisible"
			@alterVisible="alterVisible"></tutor-renew-popup>
	</view>
</template>

<script>
	import {
		getOrderDetails,
		getPayRenew,
		getPay,
		cancelOrder,
		delOrder,
		getPrice
	} from "@/http/api/order/order.js"
	import {
		getDistance
	} from '@/http/api/tutor/tutor.js'
	import Cache from '@/utils/cache'
	export default {
		data() {
			return {
				top: 0, //标题图标距离顶部距离
				marginTp: 0,
				isVisible: false,
				place: "",
				ossUrl: getApp().globalData.ossurl, //图片前缀
				inviteMerchant: {}, //邀约店铺
				status: null, //状态
				distance: '',
				orderId: '',
				timeServal: null,
				countdown: '',
				orderDetails: {}, //订单详情
			}
		},
		onLoad(options) {
			if (options) {
				this.orderId = options.orderId
				this.getData()
				getDistance(options.orderId, {
					latitude: Cache.get('latitude'),
					longitude: Cache.get('longitude')
				}).then(res => {
					if (res.code === 200) {
						this.distance = res.data && res.data.distance || ''
						console.log(res.data.distance, 'res.data.distance')
					}
				})
			}
		},
		onUnload() {
			// 在页面卸载时清除定时器
			if (this.timeServal !== null) {
				clearInterval(this.timeServal);
				this.timeServal = null; // 清空定时器ID
				console.log("定时器已销毁");
			}
		},
		methods: {
			initNavigation(e) {
				this.top = e.top;
				this.marginTp = e.height
			},
			back() {
				uni.navigateBack();
			},
			//确认续约
			clickRenew(item) {
				let that = this
				getPayRenew({
					orderId: that.orderId,
					hourNumber: item
				}).then(res => {
					if (res.code === 200) {
						getApp().globalData.initJssdk(weixin => {
							weixin.chooseWXPay({
								appId: res.data.appId,
								timestamp: res.data.timeStamp,
								nonceStr: res.data.nonceStr,
								package: res.data.packageValue,
								signType: res.data.signType,
								paySign: res.data.paySign,
								success: function(res) {
									// 支付成功后的回调函数
									that.getData()
								},
								cancel: function(res) {
									// 支付取消回调函数
									console.log(res)
								},
								// 支付失败回调函数
								fail: function(res) {
									console.log(res, '错误')
								}
							});
						})
					}
				})
			},
			alterVisible(value) {
				this.isVisible = value
			},
			getData() {
				if (this.timeServal !== null) {
					clearInterval(this.timeServal);
					this.timeServal = null; // 清空定时器ID
					console.log("定时器已销毁");
				}
				getOrderDetails(this.orderId).then(res => {
					if (res.code === 200) {
						this.orderDetails = res.data
						this.inviteMerchant = res.data.invite && res.data.invite.inviteMerchant || {}
						this.status = res.data.ordersVo && res.data.ordersVo.status || null
						let time = this.$utils.addOneHour(res.data.invite.serviceTime, res.data.invite.hourNumber)
						this.timeServal = setInterval(() => {
							this.countdown = this.getCountdown(time);
						}, 1000);
					}
				})
			},
			getCountdown(endTime) {
				const targetDate = new Date(endTime.replace(' ', 'T')); // 将目标时间转换为 Date 对象
				const now = new Date(); // 获取当前时间
				let timeDiff = targetDate - now; // 计算剩余时间的毫秒数

				// 如果目标时间已经过去，返回 0
				if (timeDiff <= 0) {
					return "00:00:00";
				}

				// 计算时分秒
				const hours = Math.floor(timeDiff / (1000 * 60 * 60));
				const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
				const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);

				// 格式化为时分秒格式
				return `${this.padZero(hours)}:${this.padZero(minutes)}:${this.padZero(seconds)}`;
			},

			// 补零函数，确保小时、分钟和秒数是两位数
			padZero(num) {
				return num < 10 ? '0' + num : num;
			},
			//获取支付参数
			getPayParms() {
				let that = this
				getPay({
					orderId: that.orderId
				}).then(res => {
					if (res.code === 200) {
						getApp().globalData.initJssdk(weixin => {
							weixin.chooseWXPay({
								appId: res.data.appId,
								timestamp: res.data.timeStamp,
								nonceStr: res.data.nonceStr,
								package: res.data.packageValue,
								signType: res.data.signType,
								paySign: res.data.paySign,
								success: function(res) {
									// 支付成功后的回调函数
									that.getData()
								},

								cancel: function(res) {
									// 支付取消回调函数
									console.log(res)

								},
								// 支付失败回调函数
								fail: function(res) {
									console.log(res)
								}
							});
						})
					}
				})
			},
			//操作
			orderClick(data, type) {
				let that = this
				switch (type) {
					case '支付': {
						that.getPayParms()
						console.log("支付");
						break;
					}
					case "取消订单": {
						console.log("取消订单");
						uni.showModal({
							title: '提示',
							content: '确认取消该订单吗？',
							showCancel: true,
							cancelColor: "#555",
							confirmColor: "#eb0909",
							confirmText: "确定",
							success(res) {
								if (res.confirm) {
									cancelOrder(data.ordersVo.id).then(res => {
										if (res.code === 200) {
											that.$utils.toast('取消成功')
											that.getData()
											that.$emit('refOrderList', true)
											uni.navigateBack()
										}
									})
								}
							}
						})
						break;
					}
					case "一件续费": {

						getPrice(data.ordersVo.id).then(res => {
							if (res.code === 200) {
								that.isVisible = true
								that.place = res.data.rates
							}
						})
						console.log("一件续费");
						break;
					}
					case "联系教练": {
						console.log("联系教练");
						if (!data.assistant.phoneNumber) {
							that.$utils.toast('教练电话不能为空')
							return
						}
						uni.makePhoneCall({
							phoneNumber: data.assistant.phoneNumber, // 替换为实际要拨打的电话号码
							success(res) {
								console.log('拨打电话成功', res);
							},
							fail(err) {
								console.error('拨打电话失败', err);
							}
						});
						break;
					}
					case "删除订单": {
						console.log("删除订单");
						uni.showModal({
							title: '提示',
							content: '确认删除该订单吗？',
							showCancel: true,
							cancelColor: "#555",
							confirmColor: "#eb0909",
							confirmText: "确定",
							success(res) {
								if (res.confirm) {
									delOrder(data.ordersVo.id).then(res => {
										if (res.code === 200) {
											that.$utils.toast('删除成功')
											that.getData()
											that.$emit('refOrderList', true)
											uni.navigateBack()
										}
									})
								}
							}
						})
						break;
					}
					case "立即评价": {
						uni.navigateTo({
							url: '/pages/mine/modules/pushEvaluate/pushEvaluate?orderId=' + data.ordersVo.id
						})
						break;
					}
					default: {
						break;
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import './orderDetails.scss';
</style>